<?php

namespace Pinenut\User\Auth;

use Pinenut\User\Auth;
use Pinenut\Model2\Finder;

class EmailPassword extends Model {
	
	/**
	 * Соль, устанавливаем внедрением зависимостей
	 *
	 * @var string
	 */
	protected static $salt;
	protected static $_type = 'emailPassword';
	
	/**
	 * Мыло
	 *
	 * @var string
	 */
	public $email;
	/**
	 * Пароль
	 *
	 * @var string
	 */
	protected $password;
	public $recoveryCode;
	public $recoveryCodeExpired;
	protected static $recoveryCodeLifeTime = 84600;
	function fields() {
		return array_merge ( parent::fields (), array (
				'email' => self::STRING,
				'password' => self::STRING,
				'recoveryCode' => self::STRING,
				'recoveryCodeExpired' => self::STRING 
		) );
	}
	function setPassword($password) {
		$this->password = md5 ( $this->email . static::$salt . $password );
	}
	function checkPassword($password) {
		return $this->password == md5 ( $this->email . static::$salt . $password );
	}
	
	/**
	 * проверяем - существует ли аккаунт с таким мылом
	 */
	function isExist() {
		return ! ! static::find ()->where ( 'email', $this->email )->count ();
	}
	
	/**
	 * проверяем - существует ли аккаунт с таким мылом и совпадает ли пароль
	 */
	function auth() {
		return static::find ()->where ( 'email', $this->email )->where ( 'password', $this->password )->active ()->one ();
	}
	/**
	 * Генерим и возвращаем новый код восстановления, обновляем его в базе
	 * 
	 * @param unknown $email        	
	 * @return NULL string
	 */
	public static function generateRecoveryCode($email) {
		$auth = static::find ()->where ( 'email', $email )->active ()->one ();
		if (! $auth) {
			return null;
		}
		
		$code = static::getNewrecoveryCode ();
		$auth->recoveryCode = $code;
		$auth->recoveryCodeExpired = time () + static::$recoveryCodeLifeTime;
		$auth->save ();
		return $code;
	}
	
	/**
	 * Генерим код
	 * 
	 * @return string
	 */
	protected static function getNewrecoveryCode() {
		return substr ( md5 ( time () ), 0, 5 );
	}
	
	/**
	 * Проверяем код
	 * 
	 * @param unknown $email        	
	 * @param unknown $code        	
	 * @return boolean
	 */
	public static function checkRecoveryCode($email, $code) {
		return ! ! static::find ()->where ( 'email', $email )
			->where ( 'recoveryCode', $code )
			->where ( 'recoveryCodeExpired', time (), Finder::OP_GTE )
			->count ();
	}
	
	/**
	 * Восстанавливаем пароль по коду
	 * 
	 * @param unknown $email        	
	 * @param unknown $code        	
	 * @param unknown $password        	
	 */
	public static function setRecoveryPassword($email, $code, $password) {
		$auth = static::find ()
			->where ( 'email', $email )
			->where ( 'recoveryCode', $code )
			->where ( 'recoveryCodeExpired', time (), Finder::OP_GTE )
			->active ()->one ();
		if (! $auth) {
			throw new \Exception ( 'Invalid recovery code' );
		}
		$auth->setPassword ( $password );
		$auth->save ();
		return $auth;
	}
}